<template>
  <div class="call-center-stats-container">
    <div
      class="customer-list-container"
      ref="customerListPage"
      v-loading.fullscreen.lock="loadingListData"
    >
      <!--搜索-->
      <div class="customer-list-search-group-container">
        <form class="base-search" onsubmit="return false;">
          <!-- <el-radio-group class="flex-1" v-model="activeName" @change="stateChangeHandler" size="medium">
            <el-radio-button label="全部"></el-radio-button>
            <el-radio-button label="已接来电"></el-radio-button>
            <el-radio-button label="未接来电"></el-radio-button>
            <el-radio-button label="呼出已接"></el-radio-button>
            <el-radio-button label="呼出未接"></el-radio-button>
          </el-radio-group> -->
          <div class="customer-list-base-search-group input-with-append-search">
            <el-input
              v-model="params.keyword"
              placeholder="请输入坐席/客户/联系人/呼叫电话搜索"
              v-trim:blur
              class="mar-r-12"
            >
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
              <el-button
                type="primary"
                slot="append"
                @click="
                  params.pageNum = 1;
                  getRecordList();
                  trackEventHandler('search');
                "
                native-type="submit"
                >搜索</el-button
              >
            </el-input>
            <el-button type="plain-third" @click="resetParams">重置</el-button>
          </div>
          <!-- <span class="advanced-search-visible-btn" @click.self="panelSearchAdvancedToggle">
            <i class="iconfont icon-filter"></i>
            高级搜索
          </span> -->
        </form>
        <!--高级搜索-->
      </div>

      <!--operation bar start-->
      <!-- <div class="operation-bar-container">
        <div class="top-btn-group">
          <el-radio-group v-model="activeName" @change="stateChangeHandler" size="medium">
            <el-radio-button label="全部"></el-radio-button>
            <el-radio-button label="已接来电"></el-radio-button>
            <el-radio-button label="未接来电"></el-radio-button>
            <el-radio-button label="呼出已接"></el-radio-button>
            <el-radio-button label="呼出未接"></el-radio-button>
          </el-radio-group>
        </div>
      </div> -->
      <!--operation bar end-->

      <!--list start-->
      <div class="customer-list-component">
        <div class="action-button-group">
          <!-- <el-dropdown
            trigger="hover"
          >
            <div class="task-ai task-flex task-font14 task-c6 cur-point bg-w">
              <span class="task-mr4 task-ml4">更多操作</span>
              <i class="iconfont icon-fdn-select task-icon"></i>
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="tableSetting.needImport">
                <div @click="openDialog('importProduct')">导入</div>
              </el-dropdown-item>
              <el-dropdown-item v-if="tableSetting.needExport">
                <div @click="exportFn(false)">导出</div>
              </el-dropdown-item>
              <el-dropdown-item >
                <div @click="exportFn(true)">导出全部</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown> -->
          <span class="el-dropdown-link cur-point" @click="showAdvancedSetting">
            选择列
            <i class="iconfont icon-fdn-select"></i>
          </span>
        </div>

        <div class="base-selection-wrapper">
          <base-selection-bar
            ref="baseSelectionBar"
            v-model="multipleSelection"
            @toggle-selection="toggleSelection"
            @show-panel="() => (multipleSelectionPanelShow = true)"
          />
        </div>

        <el-table
          :data="tableData"
          stripe
          @select-all="handleSelection"
          :row-key="getRowKey"
          header-row-class-name="common-list-table-header__v2"
          ref="multipleTable"
          class="customer-table bbx-normal-list-box"
          :border="true"
          @header-dragend="headerDragend"
        >
          <template v-for="column in columns">
            <el-table-column
              v-if="column.show"
              show-overflow-tooltip
              :fixed="column.fixed"
              :key="column.field"
              :label="column.label"
              :prop="column.field"
              :width="column.width"
              :class-name="
                column.field == 'name' ? 'customer-name-superscript-td' : ''
              "
              align="center"
              header-align="center"
            >
              <template slot-scope="scope">
                <template v-if="column.field === 'id'">
                  <span
                    :class="
                      globalIsHaveCallCenterViewDetailAuth ? 'recordId' : ''
                    "
                    @click="detail(scope.row)"
                    >{{ scope.row[column.field] }}</span
                  >
                </template>
                <template v-else-if="column.field === 'callType'">
                  {{ fmt_callType(scope.row) }}
                </template>
                <template v-else-if="column.field === 'dialPhone'">
                  {{ scope.row[column.field] }}
                  <biz-call-icon :value="scope.row[column.field]" />
                </template>
                <template v-else-if="column.field === 'customerName'">
                  <span v-if="scope.row[column.field]">{{
                    scope.row[column.field]
                  }}</span>
                  <span v-else>--</span>
                </template>
                <template v-else-if="column.field === 'sortName'">
                  <span v-if="scope.row[column.field]">{{
                    scope.row[column.field]
                  }}</span>
                  <span v-else>--</span>
                </template>
                <template v-else-if="column.field === 'linkmanName'">
                  <span v-if="scope.row[column.field]">{{
                    scope.row[column.field]
                  }}</span>
                  <span v-else>--</span>
                </template>
                <template v-else-if="column.field === 'status'">
                  <span
                    v-if="scope.row[column.field] == 0"
                    style="color: #fb602c"
                    >未解决</span
                  >
                  <span v-else-if="scope.row[column.field] == 1">已解决</span>
                  <span v-else>--</span>
                </template>
                <template v-else-if="column.field === 'handleStatus'">
                  <span
                    v-if="scope.row[column.field] == 0"
                    style="color: #fb602c"
                    >未处理</span
                  >
                  <span v-else-if="scope.row[column.field] == 1">已处理</span>
                  <span v-else>--</span>
                </template>

                <!-- <template v-else-if="column.field === 'operation'" slot-scope="scope">
                <el-button type="text" v-if="scope.row.state=='notDeal'" @click="dealDialog(scope.row)">处理</el-button>
                <el-button class="color-black" type="text" v-else @click="detail(scope.row)">详情</el-button>
              </template> -->
                <template v-else-if="column.field === 'agentName'">
                  <template v-if="isOpenData && scope.row.agentStaffId">
                    <open-data
                      type="userName"
                      :openid="scope.row.agentStaffId"
                    ></open-data>
                  </template>
                  <template v-else>
                    <span>{{ scope.row[column.field] }}</span>
                  </template>
                </template>
                <template v-else-if="column.field === 'transfered'">
                  <span>{{ scope.row[column.field] === 1 ? '是' : '否' }}</span>
                </template>
                <template v-else>
                  <pre class="pre-text">{{ scope.row[column.field] }}</pre>
                </template>
              </template>
            </el-table-column>
          </template>
        </el-table>

        <div class="table-footer">
          <div class="list-info">
            共<span class="level-padding">{{ totalItems }}</span
            >记录
          </div>
          <el-pagination
            class="customer-table-pagination"
            background
            @current-change="jump"
            @size-change="handleSizeChange"
            :page-sizes="defaultTableData.defaultPageSizes"
            :page-size="params.pageSize"
            :current-page="params.pageNum"
            layout="prev, pager, next, sizes, jumper"
            :total="totalItems"
          ></el-pagination>
        </div>
      </div>
      <!--list end-->

      <base-table-advanced-setting ref="advanced" @save="modifyColumnStatus" />

      <search-panel ref="searchPanel">
        <div class="advanced-search-btn-group" slot="footer">
          <el-button type="plain-third" @click="resetParams">重置</el-button>
          <el-button type="primary" @click="powerfulSearch" native-type="submit"
            >搜索</el-button
          >
        </div>
      </search-panel>
    </div>
    <!-- 处理未接来电的对话框 -->
    <el-dialog
      title="处理未接来电"
      :visible.sync="missCallDialogVisible"
      width="30%"
      @close="missCallDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="missCallForm"
        ref="missCallFormRef"

        label-position="top"
      >
        <el-form-item label="呼叫电话">
          {{ missCallForm.dialPhone }}
          <span
            class="make-phone-call"
            v-if="hasCallAuth"
            @click="makePhoneCall(missCallForm.dialPhone)"
            >拨打电话<i class="iconfont icon-dianhua1"></i
          ></span>
        </el-form-item>

        <el-form-item label="处理状态">
          <el-radio-group v-model="missCallForm.handleStatus">
            <el-radio :label="0">未处理</el-radio>
            <el-radio :label="1">已处理</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="handleRemark">
          <el-input
            type="textarea"
            placeholder="请输入备注"
            v-model="missCallForm.handleRemark"
            maxlength="500"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="missCallDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deal">确 认</el-button>
      </span>
    </el-dialog>

    <!-- start 导出s -->
    <base-export-group
      ref="exportPanel"
      :alert="exportAlert"
      :columns="exportColumns"
      :build-params="buildExportParams"
      :group="true"
      :needchoose-break="false"
      method="post"
      :action="callCenterStage"
      :export-type="'free'"
      :key-id="`test-list`"
      :export-skip-select="false"
    />
    <!-- end 导出e -->
  </div>
</template>

<script>
import { isOpenData, openAccurateTab } from '@src/util/platform';
import _ from 'lodash';
import { parse } from '@src/util/querystring';
import SearchPanel from '../component/SearchPanelSobot';
import * as CallCenterApi from '@src/api/CallCenterApi';
import { ctiCallOut } from '@src/util/ctisdk';
import { getRootWindow } from '@src/util/dom';
/* mixin */
import ThemeMixin from '@src/mixins/themeMixin/index.ts';
import AuthMixin from '@src/mixins/authMixin';

import { callCenterStage } from '@src/api/Export';
import { safeNewDate } from '@src/util/time';
import { PageRoutesTypeEnum } from '@model/enum/PageRoutesEnum';
import { formatDate, useFormTimezone, formatAddress } from 'pub-bbx-utils'
import { defaultTableData } from '@src/util/table'
const { disposeFormListViewTime } = useFormTimezone()
import { fmtDist } from '@src/util/addressUtil';

export default {
  name: 'stage-tian-run',
  mixins: [ThemeMixin, AuthMixin],
  props: {
    initData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      defaultTableData,
      isOpenData,
      pending: false,
      loadingListData: false,
      activeName: '全部',
      callState: {},
      statisticsRecord: {},
      params: {
        // orderDetail: {},
        // moreConditions: {
        //   conditions: []
        // },
        keyword: '',
        pageNum: 1,
        pageSize: 10,
      },
      totalItems: 0,
      multipleSelection: [],
      defaultAddress: [],

      recordList: [],
      columns: this.fixedColumns(),
      selectedLimit: 500,
      columnNum: 1,
      tableKey: (Math.random() * 1000) >> 2,
      missCallDialogVisible: false,
      missCallForm: {
        id: '',
        dialPhone: '',
        handleStatus: 0,
        handleRemark: '',
      },
      callCenterStage,
    };
  },
  computed: {
    // 处理时间后的列表数据
    tableData(){
      return disposeFormListViewTime(this.recordList, this.columns)
    },
    hasCallAuth() {
      return !!getRootWindow(window).CTI;
    },
    panelWidth() {
      return `${420 * this.columnNum}px`;
    },

    exportColumns() {
      let arr = [...this.columns]
        .filter(item => item.formType !== 'doSome')
        .map(field => {
          if (
            ['customer', 'productTemplate', 'remindCount'].some(
              key => key === field.fieldName
            ) ||
            field.formType === 'info'
          ) {
            field.export = false;
          } else {
            field.export = true;
          }
          return field;
        });

      let arr_ = [
        {
          label: '呼叫中心',
          value: 'callCenterStageExport',
          columns: arr,
        },
      ];
      return arr_;
    },
  },

  mounted() {
    const query = parse(window.location.search) || {};
    if (query.keyword) {
      this.params.keyword = query.keyword;
    }
    // this.getTodayCallState()
    // this.getTodayStatisticsRecord()
    this.columns = this.buildTableColumn();
    this.getRecordList();

    // this.search()
  },

  methods: {
    // 处理未接来电打电话
    async makePhoneCall(tel) {
      if (!tel) return;
      try {
        ctiCallOut(tel); // taskType:'handle'
      } catch (error) {
        console.error(error);
      }
    },
    async getRecordList() {
      this.loadingListData = true;
      try {
        let { code, message, result } = await CallCenterApi.getZhiChiRecordList(
          this.params
        );
        if (code != 0) return this.$message.error(message || '内部错误');
        this.loadingListData = false;
        if (!result || !result.list) {
          this.recordList = [];
          this.totalItems = 0;
          this.params.pageNum = 1;
        } else {
          const { total, pageNum, list } = result;
          this.recordList = list.map(c => {
            c.pending = false;
            return c;
          });
          this.totalItems = total;
          this.params.pageNum = pageNum;
          this.matchSelected(); // 把选中的匹配出来
        }
      } catch (error) {
        this.loadingListData = false;
        console.error(error);
      }
    },

    getTodayCallState() {
      CallCenterApi.getTodayCallState()
        .then(({ code, message, result }) => {
          if (code != 0) return this.$message.error(message || '内部错误');
          this.callState = result || {};
        })
        .catch(err => {
          console.error(err);
        });
    },

    getTodayStatisticsRecord() {
      CallCenterApi.getTodayStatisticsRecord()
        .then(({ code, message, result }) => {
          if (code != 0) return this.$message.error(message || '内部错误');
          this.statisticsRecord = result || {};
        })
        .catch(err => {
          console.error(err);
        });
    },

    stateChangeHandler(state) {
      // 切换tab
      this.activeName = state;
      this.columns.forEach(col => {
        if (col.field == 'handleStatus') {
          this.$set(
            col,
            'show',
            this.activeName === '全部' || this.activeName === '未接来电'
          );
        } else if (col.field == 'status') {
          this.$set(col, 'show', this.activeName != '未接来电');
        }
      });
      switch (state) {
        case '全部':
          this.params.callType = '';
          this.params.state = '';
          break;
        case '已接来电':
          this.params.callType = 'normal';
          this.params.state = 'dealing';
          break;
        case '未接来电':
          this.params.callType = 'normal';
          this.params.state = 'notDeal';
          break;
        case '呼出已接':
          this.params.callType = 'dialout';
          this.params.state = 'dealing';
          break;
        case '呼出未接':
          this.params.callType = 'dialout';
          this.params.state = 'notDeal';
          break;
        default:
          break;
      }
      this.getRecordList();
    },

    powerfulSearch() {
      // 高级搜索
      let keyword = this.params.keyword;
      this.params = {
        keyword,
        pageNum: 1,
        pageSize: 10,
      };
      // this.params.pageNum = 1
      // this.params.moreConditions = this.$refs.searchPanel.buildParams()
      const p = this.$refs.searchPanel.buildParams();
      const moreConditions = p.conditions || [];
      this.params.customerId = p.customerId || '';
      this.params.linkmanId = p.linkmanId || '';
      moreConditions.forEach(item => {
        if (item.property == 'sortId') {
          // 咨询分类
          this.params.sortId = item.value[0].id || '';
        } else if (item.property == 'ringTime') {
          this.params.ringStartTime = item.betweenValue1
          this.params.ringEndTime = item.betweenValue2
        } else if (item.property == 'beginTime') {
          this.params.beginTimeStart = item.betweenValue1
          this.params.beginTimeEnd = item.betweenValue2
        } else if (item.property == 'endTime') {
          this.params.endTimeStart = item.betweenValue1
          this.params.endTimeEnd = item.betweenValue2
        } else {
          this.params[item.property] = item.value || '';
        }
      });
      // console.log(this.params);
      this.getRecordList();
      // this.search()
    },
    showAdvancedSetting() {
      // window.TDAPP.onEvent('pc：通话记录-选择列事件')

      this.$refs.advanced.open(this.columns);
    },
    // createCustomerTab(customerId) {
    //   let fromId = window.frameElement.getAttribute('id')

    //   this.$platform.openTab({
    //     id: `customer_view_${customerId}`,
    //     title: '客户详情',
    //     close: true,
    //     url: `/customer/view/${customerId}?noHistory=1`,
    //     fromId
    //   })
    // },

    formatAddress(ad) {
      if (null == ad) return '';

      return fmtDist(ad);
    },
    formatCustomizeAddress(ad) {
      if (null == ad) return '';

      return formatAddress(ad);
    },

    revertStorage() {
      const { pageSize, column_number } = this.getLocalStorageData();
      if (pageSize) {
        this.params.pageSize = pageSize;
      }
      if (column_number) this.columnNum = Number(column_number);
    },
    // search() {
    //   const params = this.buildParams()

    //   this.loadingListData = true

    //   return this.$http
    //     .post('/customer/list', params)
    //     .then(res => {
    //       if (!res || !res.list) {
    //         this.customers = []
    //         this.totalItems = 0
    //         this.params.pageNum = 1
    //       } else {
    //         const { total, pageNum, list } = res

    //         this.customers = list.map(c => {
    //           c.pending = false
    //           return c
    //         })

    //         this.totalItems = total
    //         this.params.pageNum = pageNum
    //         this.matchSelected() // 把选中的匹配出来
    //       }

    //       return res
    //     })
    //     .then(() => {
    //       this.$refs.customerListPage.scrollTop = 0
    //       this.loadingListData = false
    //     })
    //     .catch(err => {
    //       this.loadingListData = false
    //       console.error('err', err)
    //     })
    // },
    buildParams() {
      const sm = Object.assign({}, this.params);
      let params = {
        keyword: sm.keyword,
        pageSize: sm.pageSize,
        pageNum: sm.pageNum,
      };

      // if (Object.keys(sm.orderDetail || {}).length) {
      //   params.orderDetail = sm.orderDetail
      // }

      // if (
      //   Object.keys(sm.moreConditions).length > 1 ||
      //   sm.moreConditions.conditions.length
      // ) {
      //   params = {
      //     ...params,
      //     ...sm.moreConditions
      //   }
      // }

      return params;
    },

    jump(pageNum) {
      this.params.pageNum = pageNum;
      // this.search()
      this.getRecordList();
    },
    handleSizeChange(pageSize) {
      this.saveDataToStorage('pageSize', pageSize);
      this.params.pageNum = 1;
      this.params.pageSize = pageSize;
      // this.search()
      this.getRecordList();
    },
    handleSelection(selection) {
      let tv = this.computeSelection(selection);
      let original = this.multipleSelection.filter(ms =>
        this.customers.some(cs => cs.id === ms.id)
      );
      let unSelected = this.customers.filter(c =>
        original.every(oc => oc.id !== c.id)
      );

      if (tv.length > this.selectedLimit) {
        this.$nextTick(() => {
          original.length > 0
            ? unSelected.forEach(row => {
                this.$refs.multipleTable.toggleRowSelection(row, false);
              })
            : this.$refs.multipleTable.clearSelection();
        });
        return this.$platform.alert(`最多只能选择${this.selectedLimit}条数据`);
      }
      this.multipleSelection = tv;

      this.$refs.baseSelectionBar?.openTooltip();
    },
    computeSelection(selection) {
      let tv = [];
      tv = this.multipleSelection.filter(ms =>
        this.customers.every(c => c.id !== ms.id)
      );
      tv = _.uniqWith([...tv, ...selection], _.isEqual);
      return tv;
    },
    toggleSelection(rows) {
      let isNotOnCurrentPage = false;
      let row = undefined;

      if (rows) {
        for (let i = 0; i < rows.length; i++) {
          row = rows[i];
          isNotOnCurrentPage = this.recordList.every(item => {
            return item.id !== row.id;
          });
          if (isNotOnCurrentPage) return;
        }
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
        this.multipleSelection = [];
      }
    },
    // columns
    modifyColumnStatus(event) {
      let columns = event.data || [];
      let colMap = columns.reduce(
        (acc, col) => (acc[col.field] = col) && acc,
        {}
      );

      this.columns.forEach(col => {
        let newCol = colMap[col.field];
        if (null != newCol) {
          this.$set(col, 'show', newCol.show);
          this.$set(col, 'width', newCol.width);
        }
      });

      const showColumns = this.columns.map(c => ({
        field: c.field,
        show: c.show,
        width: c.width,
      }));
      this.saveDataToStorage('columnStatus', showColumns);
    },
    /**
     * @description 表头更改
     */
    headerDragend(newWidth, oldWidth, column, event) {
      let data = this.columns
        .map(item => {
          if (item.fieldName === column.property) {
            item.width = column.width;
          }
          return {
            field: item.field,
            show: item.show,
            width: item.width,
          };
        });
      this.modifyColumnStatus({ type: 'column', data });
    },
    // common methods
    getLocalStorageData() {
      const dataStr = localStorage.getItem('callCenterListDataTianRun') || '{}';
      return JSON.parse(dataStr);
    },
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      localStorage.setItem('callCenterListDataTianRun', JSON.stringify(data));
    },
    buildTableColumn() {
      const localStorageData = this.getLocalStorageData();
      let columnStatus = localStorageData.columnStatus || [];
      let localColumns = columnStatus
        .map(i => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col) => (acc[col.field] = col) && acc, {});

      let baseColumns = this.fixedColumns();
      let dynamicColumns = this.getDynamicColumns().map(field => {
        let sortable = false;
        let minWidth = null;

        if (['date', 'datetime', 'number'].indexOf(field.formType) >= 0) {
          sortable = 'custom';
          minWidth = 100;
        }

        if (field.displayName && field.displayName.length > 4) {
          minWidth = field.displayName.length * 20;
        }

        // if (sortable && field.displayName.length >= 4) {
        //   minWidth = 125
        // }

        if (field.formType === 'datetime') {
          minWidth = 180;
        }

        return {
          label: field.displayName,
          field: field.fieldName,
          formType: field.formType,
          minWidth: typeof minWidth == 'number' ? minWidth : `${minWidth}px`,
          sortable,
          isSystem: field.isSystem,
        };
      });

      let columns = [...baseColumns, ...dynamicColumns].map(col => {
        let show = col.show === true;
        let width = col.width;
        let localField = localColumns[col.field];

        if (null != localField) {
          width =
            typeof localField.width == 'number' ? `${localField.width}px` : '';
          show = localField.show !== false;
        }
        console.info('width::', width);

        col.show = show;
        col.width = width;
        col.type = 'column';

        return col;
      }).filter(v => {

        if (v.fieldName == 'taskId') {
          return this._isShowTaskModule
        }

        return v
      });
      return columns;
    },
    resetParams() {
      // window.TDAPP.onEvent('pc：客户管理-重置事件')
      this.$refs.searchPanel.resetParams();

      this.params = {
        keyword: '',
        pageNum: 1,
        pageSize: this.params.pageSize,
        // orderDetail: {},
        // moreConditions: {
        //   conditions: []
        // }
      };
      // this.getRecordList()
      // this.search()
      this.reloadTab();
    },
    // match data
    matchSelected() {
      if (!this.multipleSelection.length) return;
      const selected =
        this.recordList.filter(c => {
          if (this.multipleSelection.some(sc => sc.id === c.id)) {
            this.multipleSelection = this.multipleSelection.filter(
              sc => sc.id !== c.id
            );
            this.multipleSelection.push(c);
            return c;
          }
        }) || [];

      this.$nextTick(() => {
        this.toggleSelection(selected);
      });
    },
    fmt_callType(row) {
      // 呼叫类型
      let res = '';
      if (row.callType === 'normal') {
        res = row.state === 'dealing' ? '已接来电' : '未接来电';
      } else if (row.callType === 'dialout') {
        res = row.state === 'dealing' ? '呼出已接' : '呼出未接';
      }
      return res;
    },
    fixedColumns() {
      return [
        {
          label: '通话ID',
          field: 'id',
          show: true,
          minWidth: '150px',
          width: '160px',
        },
        {
          label: '接待坐席',
          field: 'agent',
          // width: '150px',
          show: true,
        },
        {
          label: '坐席账号',
          field: 'agentName',
          // width: '150px',
          show: true,
        },
        // {
        //   label: '呼叫类型',
        //   field: 'callType',
        //   // width: '100px',
        //   show: true
        // },
        {
          label: '来去电时间',
          field: 'ring',
          minWidth: '180px',
          show: true,
        },
        // {
        //   label: '处理状态',
        //   field: 'handleStatus',
        //   // width: '160px',
        //   show: true
        // },
        {
          label: '呼叫电话',
          field: 'dialPhone',
          show: true,
          // width: '110px'
        },
        {
          label: '客户',
          field: 'customerName',
          show: true,
          // width: '100px'
        },
        {
          label: '联系人',
          field: 'linkmanName',
          show: true,
          // width: '150px'
        },
        // {
        //   label: '消耗话费(元)',
        //   field: 'cost',
        //   show: true,
        //   // width: '150px'
        // },
        // {
        //   label: '是否转接',
        //   field: 'transfered',
        //   show: true,
        //   // width: '150px'
        // },
        // {
        //   label: '转接手机号',
        //   field: 'transferPhone',
        //   show: true,
        //   // width: '150px'
        // },
        // {
        //   label: '操作',
        //   field: 'operation',
        //   minWidth: '60px',
        //   show: true,
        //   fixed: 'right'
        // }
      ];
    },
    getDynamicColumns() {
      return [
        {
          displayName: '归属地',
          label: '归属地',
          fieldName: 'attribution',
          // width: '150px',
          show: false,
        },
        {
          displayName: '通话开始时间',
          label: '通话开始时间',
          fieldName: 'beginTime',
          minWidth: '180px',
          show: false,
        },
        {
          displayName: '通话结束时间',
          label: '通话结束时间',
          fieldName: 'endTime',
          minWidth: '180px',
          show: false,
        },
        {
          displayName: '通话时长',
          label: '通话时长',
          fieldName: 'talkTime',
          // width: '150px',
          show: false,
        },
        // {
        //   displayName: '关联工单',
        //   label: '关联工单',
        //   fieldName: 'taskId',
        //   // width: '150px',
        //   show: false
        // },
        // {
        //   displayName: '关联事件',
        //   label: '关联事件',
        //   fieldName: 'eventId',
        //   // width: '150px',
        //   show: false
        // },
      ];
    },
    panelSearchAdvancedToggle() {
      // window.TDAPP.onEvent('pc：客户管理-高级搜索事件')
      this.$refs.searchPanel.open();
      this.$nextTick(() => {
        let forms = document.getElementsByClassName('advanced-search-form');
        for (let i = 0; i < forms.length; i++) {
          let form = forms[i];
          form.setAttribute('novalidate', true);
        }
      });
    },
    // TalkingData事件埋点
    trackEventHandler(type) {
      // if (type === 'search') {
      //   window.TDAPP.onEvent('pc：呼叫工作台-搜索事件')
      //   return
      // }
    },
    getRowKey(row) {
      return row.id;
    },
    detail(row) {
      if (!this.globalIsHaveCallCenterViewDetailAuth) return;

      // let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `callcenter_view_${row.id}`,
      //   title: '通话详情',
      //   close: true,
      //   url: `/setting/callcenter/view?id=${row.id}&phone=${row.dialPhone}`,
      //   fromId: 'M_CASE'
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCallcenterView,
        key: row.id,
        params: `id=${row.id}&phone=${row.dialPhone}`,
        fromId: 'M_CASE',
      });
    },
    missCallDialogClosed() {
      this.$refs.missCallFormRef.resetFields();
    },
    dealDialog(item) {
      this.missCallDialogVisible = true;
      this.missCallForm.id = item.id;
      this.missCallForm.dialPhone = item.dialPhone;
    },
    async deal(row) {
      // 处理未接来电
      // console.info('form::', this.missCallForm);
      try {
        this.pending = true;
        const params = this.missCallForm;
        delete params.dialPhone;
        const { code, message } = await CallCenterApi.updateHandleStatus(
          params
        );
        if (code !== 0)
          return this.$platform.notification({
            title: '处理失败',
            message: message || '',
            type: 'error',
          });
        this.pending = false;
        this.missCallDialogVisible = false;
        this.missCallDialogClosed();
        this.$platform.notification({
          title: '处理成功',
          type: 'success',
        });
        this.getRecordList();
      } catch (error) {
        this.pending = false;
        console.error(error);
      }
    },
    /**
     * @des 导出会话记录
     */
    exportFn(exportAll) {
      // if (this.tableSetting.fastExport) {
      //   // 快速导出
      //   window.location.href = this.tableSetting.fastExport;
      //   return;
      // }
      let ids = [];
      let fileName = `${formatDate(
        safeNewDate(),
        'YYYY-MM-DD'
      )}${'呼叫中心'}.xlsx`;
      if (!exportAll) {
        if (!this.multipleSelection.length)
          return this.$platform.alert('请选择要导出的数据');
        ids = this.selectedIds;
      }
      this.$refs.exportPanel.open(ids, fileName);
    },
    /**
     * @description 导出提示
     */
    exportAlert(result, params = {}) {
      this.$platform.alert(result.message);
    },
    /**
     * 导出数据
     */
    exportData(number, list = []) {
      const export_list = this.exportColumns;
      if (!list.length) return;
      if (number === 3) {
        let cardField = [];
        export_list
          .filter((item, index) => {
            return index > 2;
          })
          .forEach(v => {
            v.columns.forEach(item => {
              cardField.push(item);
            });
          });
        return cardField
          .map(v => {
            let bool = list.some(item => {
              if (v.exportAlias) {
                return v.exportAlias === item;
              }
              return v.fieldName === item;
            });
            if (bool) {
              return v.exportAlias ? v.exportAlias : v.fieldName;
            }
          })
          .filter(item => {
            return item;
          });
      }

      return export_list[number].columns
        .filter(v => {
          let bool = list.some(item => {
            if (v.exportAlias) {
              return v.exportAlias === item;
            }
            return v.field === item || v.fieldName === item;
          });
          return bool;
        })
        .map(v => (v.exportAlias ? v.exportAlias : v.field || v.fieldName));
    },
    /**
     * @description 构建导出参数
     * @return {Object} 导出参数
     */
    buildExportParams(checkedMap, ids, exportOneRow) {
      const { callCenterStageExport } = checkedMap;
      const rootWindow = getRootWindow(window);

      let exportAll = !ids || !ids.length;
      const all = exportAll
        ? {
            ...this.params,
            ids: this.selectedIds,
            // tagIds: loginUser.tagIds,
            // tenantId: JSON.parse(rootWindow._init).user.tenantId,
          }
        : {
            ids: this.selectedIds,
            // tagIds: loginUser.tagIds,
            // tenantId: JSON.parse(rootWindow._init).user.tenantId,
          };

      let exportSearchModel = {};
      let params = {
        exportSearchModel: JSON.stringify({
          ...all,
          ...{
            exportTotal: exportAll ? this.totalItems : this.selectedIds.length,
          },
        }),
      };
      /** ********************* *********************/
      // 信息
      let export_product = this.exportData(0, callCenterStageExport);

      params['ids'] = exportAll ? '' : this.selectedIds.join(',');

      params['checked'] = export_product.join(',');

      return params;
    },
    // 刷新页面
    reloadTab() {
      let fromId = window.frameElement.getAttribute('data-id');
      console.log(fromId);
      this.$platform.refreshTab(fromId);
    },
  },

  components: {
    [SearchPanel.name]: SearchPanel,
  },
};
</script>

<style lang="scss" scoped>
.make-phone-call {
  color: #ffffff;
  background: #55b7b4;
  border-color: #55b7b4;
  padding: 3px 5px;
  border-radius: 4px;
  height: 24px;
  line-height: 24px;
  margin-left: 5px;
  i {
    cursor: pointer;
  }
}
.call-center-stats-container {
  margin: 12px;
  .stats-station-header {
    display: flex;
    border-radius: 4px;
    background-color: #fafafa;
    padding: 16px;
    align-items: center;
    p {
      flex: 1;
      margin: 0;
      font-size: 16px;
      color: #051a13;
      font-weight: 500;
      i {
        color: #595959;
        margin-left: 10px;
      }
      span {
        font-size: 14px;
        font-weight: 400;
      }
      .money {
        color: #fb602c;
      }
    }
  }

  .stats-station-today-header {
    border-radius: 4px 4px 0 0;
    background-color: #fafafa;
    height: 48px;
    line-height: 48px;
    font-size: 16px;
    font-weight: 500;
    color: #051a13;
    align-items: center;
    margin-top: 12px;
    padding-left: 16px;
  }

  .stats-station-today-content {
    display: flex;
    flex-flow: row nowrap;
    border-radius: 4px;
    overflow: hidden;
    padding-top: 1px;
    margin-bottom: 12px;
    justify-content: flex-end;

    .stats-station-card {
      flex: 1;
      background-color: #fff;
      border-right: 1px solid #eee;
      .card-content {
        p {
          display: flex;
          padding-left: 20px;
        }
        h3 {
          padding-left: 20px;
        }
        .icon-huru {
          color: #6ecf40;
          margin-right: 8px;
        }
        .icon-huchu {
          color: #ffae00;
          margin-right: 8px;
        }
      }
      .card-bottom {
        background: #fafafa;
        height: 80px;
        line-height: 80px;
        padding-left: 20px;
        padding: 10px 0 10px 20px;
        h4 {
          font-weight: 400;
          margin: 0;
          height: 30px;
          line-height: 30px;
        }
      }
      p {
        padding: 15px 0 8px;
        margin: 0;
        font-size: 14px;
      }

      h3 {
        font-weight: 400;
        font-size: 24px;
        line-height: 34px;
        margin: 0;
        padding: 5px 0 20px 0;
      }

      &:first-child {
        margin-left: 0;
      }
    }
  }

  .customer-list-container {
    height: 100%;
    overflow: auto;

    .panel-title {
      font-size: 16px;
      line-height: 60px;
      padding: 0 25px;
      color: rgb(132, 138, 147);
      border-bottom: 1px solid rgb(242, 248, 247);
      font-weight: normal;
      display: flex;
      justify-content: space-between;
      .iconfont:hover {
        cursor: pointer;
      }
    }
  }

  // search
  .customer-list-search-group-container {
    .advanced-search-function,
    .base-search {
      background: #fff;
      border-radius: 4px 4px 0 0;
    }

    .base-search {
      font-size: 14px;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding: 16px 16px 0;

      .customer-list-base-search-group {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .el-input {
          width: 300px;
          input {
            width: 300px;
            border-radius: 4px 0 0 4px;
          }
        }

        a {
          line-height: 33px;
        }
      }

      .advanced-search-visible-btn {
        font-size: 14px;
        line-height: 32px;
        // @include fontColor();
        color: $color-primary;
        border-color: $color-primary;
        background: #fff;
        padding: 0 13px;
        white-space: nowrap;

        &:hover {
          cursor: pointer;
        }
      }
    }

    .advanced-search-form {
      overflow: auto;
      padding: 10px 0 63px 0;
      height: calc(100% - 51px);

      .form-item-container {
      }

      .two-columns {
        display: flex;
        flex-wrap: wrap;
        .el-form-item {
          width: 50%;
        }
      }

      .el-form-item {
        .el-form-item__content,
        .el-select,
        .base-dist-picker,
        .el-cascader,
        .el-date-editor {
          width: 290px;
        }
      }

      .advanced-search-btn-group {
        display: flex;
        justify-content: flex-end;
        width: 100%;
        position: absolute;
        bottom: 0px;
        background: #fff;
        padding: 15px 20px;

        .base-button {
          margin: 0 10px;
        }
      }
    }

    .advanced-search-function {
      margin-top: 10px;
      padding-bottom: 10px;

      h4 {
        border-bottom: 1px solid #f4f4f4;
        padding: 10px;
      }

      .el-row {
        padding: 5px 0;
      }
      .input-label {
        text-align: right;
        line-height: 32px;
        padding-right: 0;
      }
    }
  }

  // list
  .customer-list-component {
    // padding-top: 10px;
    /*min-height: calc(100% - 100px);*/
    border-radius: 4px;
    overflow: hidden;

    .action-button-group {
      background: #fff;
      padding: 16px;
      text-align: right;
    }

    .el-dropdown-btn {
      padding: 0 15px;
      display: inline-block;
      outline: none;
      .iconfont {
        margin-left: 5px;
        font-size: 12px;
      }

      &:hover {
        cursor: pointer;
      }
    }

    .el-table__fixed-right {
      // 操作栏固定到最右侧
      // top: 10px;
    }

    .customer-table {
      // padding: 16px;

      &:before {
        height: 0;
      }

      .customer-table-header th {
        background: #fafafa;
        color: $text-color-primary;
        font-weight: normal;
      }

      .view-detail-btn {
        width: 100%;
        @include fontColor();
      }

      .view-detail-btn {
        @include fontColor();
      }

      .select-column .el-checkbox {
        position: relative;
        top: 3px;
      }
    }

    .table-footer {
      display: flex;
      justify-content: space-between;
      padding: 0px 10px 10px 10px;
      background: #fff;
      border-radius: 0 0 4px 4px;

      .list-info {
        font-size: 13px;
        line-height: 32px;
        margin: 0;
        color: #767e89;

        .iconfont {
          position: relative;
          top: 1px;
        }
      }

      .el-pagination__jump {
        margin-left: 0;
      }
    }
  }

  .customer-panel-btn {
    float: right;
    cursor: pointer;
    font-size: 14px;
    margin-right: 5px;

    &:hover {
      @include fontColor();
    }
  }

  // -------- customer selected panel --------
  .customer-selected-count {
    @include fontColor();
    padding: 0 3px;
    width: 15px;
    text-align: center;
    cursor: pointer;
    font-size: 13px;
  }

  .customer-selected-panel {
    font-size: 14px;
    height: calc(100% - 51px);

    .customer-selected-tip {
      padding-top: 80px;

      img {
        display: block;
        width: 240px;
        margin: 0 auto;
      }

      p {
        text-align: center;
        color: #9a9a9a;
        margin: 30px 0 0 0;
        line-height: 20px;
      }
    }

    .customer-selected-list {
      height: 100%;
      padding: 10px;
      overflow-y: auto;

      .customer-selected-row {
        display: flex;
        flex-flow: row nowrap;
        line-height: 36px;
        border-bottom: 1px solid #ebeef5;
        font-size: 13px;

        &:hover {
          background-color: #f5f7fa;

          .customer-selected-delete {
            visibility: visible;
          }
        }
      }

      .customer-selected-head {
        background-color: #f0f5f5;
        color: #333;
        font-size: 14px;
      }

      .customer-selected-sn {
        padding-left: 10px;
        width: 150px;
        @include text-ellipsis;
      }

      .customer-selected-name {
        padding-left: 10px;
        flex: 1;
        @include text-ellipsis;
      }

      .customer-selected-delete {
        width: 36px;
      }

      .customer-selected-row button.customer-selected-delete {
        padding: 0;
        width: 36px;
        height: 36px;
        border: none;
        background-color: transparent;
        outline: none;
        color: #646b78;
        visibility: hidden;

        i {
          font-size: 14px;
        }

        &:hover {
          color: #e84040;
        }
      }
    }
  }

  // operation
  .customer-columns-dropdown-menu {
    max-height: 300px;
    overflow: auto;
    .el-dropdown-menu__item {
      padding: 0;
    }
    .el-checkbox {
      width: 100%;
      padding: 5px 15px;
      margin: 0;
    }
  }

  .operation-bar-container {
    background: #fff;
    border-radius: 0;
    display: flex;
    justify-content: space-between;
    margin-bottom: 12px;
    border-radius: 0 0 4px 4px;
  }

  // superscript
  .customer-name-superscript-td {
    padding: 0 !important;
    & > div {
      height: 43px;
      line-height: 43px !important;
      a {
        display: inline-block;
        height: 43px;
        line-height: 43px;
      }
    }
  }
}
.color-black {
  color: $text-color-primary;
}
.recordId {
  color: $color-primary-light-6;
  cursor: pointer;
}
.recordId:hover {
  text-decoration: underline;
}
</style>
